package 笔试;

public class 岛屿数量字符串 {
    int[][] nextP = {{0, 1},{0, -1},{1, 0},{-1, 0}};
    public int numIslands (String[][] grid) {
        // write code here
        int count = 0;
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if("1".equals(grid[i][j])) {
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }

    public void dfs(String[][] grid, int i, int j) {

        grid[i][j] = "0";
        for(int z = 0; z < 4; z++) {
            int newI = i + nextP[z][0];
            int newJ = j + nextP[z][1];
            if(newI < 0 || newI >= grid.length || newJ < 0 || newJ >= grid[0].length) continue;
            if("1".equals(grid[newI][newJ])) {
                dfs(grid, newI, newJ);
            }
        }
    }
}
